package com.platform.modules.wallet.take;

import com.platform.modules.wallet.event.RedPacketRefundEvent;
import com.platform.modules.wallet.event.TransferRefundEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TaskService {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    private TaskService taskService;

    private DelayQueue<Task> delayQueue =  new DelayQueue<Task>();

    @PostConstruct
    private void init() {
        taskService = this;

        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
//                        Task task = delayQueue.take();
//                        task.run();
                        processTask(delayQueue.take());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void addTask(Task task){

        if (task instanceof TransferRefundTask){
            log.info("添加延迟播放结束任务：{},时间：{}秒", task.getId(),task.getDelay(TimeUnit.SECONDS));
        }

        if (contains(task)){
            return ;
        }

        delayQueue.add(task);
    }

    public void removeTask(Task task){
        delayQueue.remove(task);
    }


    /**
     *
     * 判断任务是否已经存在
     *
     * @param playId
     * @return
     */
    public boolean contains(Integer playId){

        if(delayQueue.contains(new TransferRefundTask(String.valueOf(playId), 1 * 1000))){
            return true;
        }
        return false;
    }

    /**
     * 判断任务是否已经存在
     * @param task
     * @return
     */
    public boolean contains(Task task){

        if(delayQueue.contains(task)){
            return true;
        }
        return false;
    }

    /**
     * 内部执行延时任务
     * @param task
     */
    private void processTask(Task task) {


        log.info("执行延时任务：{}", task.getId());

        if (task instanceof TransferRefundTask){
            applicationEventPublisher.publishEvent(new TransferRefundEvent(task.getId()));
        }else if (task instanceof RedPacketRefundTask){
            applicationEventPublisher.publishEvent(new RedPacketRefundEvent(task.getId()));
        }
        
        //根据task中的data自定义数据来处理相关逻辑，例 if (task.getData() instanceof XXX) {}
    }
}
